//
//  ChromeProgressBar.m
//  ChromeProgressBar
//
//  Created by Mario Nguyen on 01/12/11.
//  Copyright (c) 2012 Mario Nguyen. All rights reserved.
//

#import "ChromeProgressBar.h"
#import "MyUtilities.h"
@implementation ChromeProgressBar{
    NSTimer* loadTimer;
}

double FAKE_PROGRESS_THRESHOLD = 0.95f;

- (void)drawRect:(CGRect)rect {
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    CGRect progressRect = rect;

    //change bar width on progress value (%)
    progressRect.size.width *= [self progress];
 
    //Fill color
    CGContextSetFillColorWithColor(ctx, [_tintColor CGColor]);
    CGContextFillRect(ctx, progressRect);
    
    //Hide progress with fade-out effect
    if (self.progress == 1.0f) {
       // _animationTimer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(hideWithFadeOut) userInfo:nil repeats:YES];
        [self hideWithFadeOut];

    }

}

-(void)start{
    if(loadTimer == nil){
        loadTimer = [NSTimer scheduledTimerWithTimeInterval:0.2f target:self selector:@selector(onRandomizeProgress) userInfo:nil repeats:YES];
    }
    
}
-(void)pause{
    //loadTimer
}
-(void)onRandomizeProgress{
    int randomNumber = [MyUtilities randomWithMin:0 AndMax:3];
    double progressNumber = randomNumber*1.0f / 100;
    if(self.progress + progressNumber > FAKE_PROGRESS_THRESHOLD){
        self.progress = FAKE_PROGRESS_THRESHOLD;
    }
    else{
        self.progress += progressNumber;
    }
}

- (void) hideWithFadeOut {
    [UIView animateWithDuration:0.5f animations:^{
        self.alpha=0;
    } completion:^(BOOL finished) {
        self.progress=0;
        self.alpha=1;
        
    }];
    /*
    //initialize fade animation 
    CATransition *animation = [CATransition animation];
    animation.type = kCATransitionFade;
    animation.duration = 0.5;
    [self.layer addAnimation:animation forKey:nil];
    
    //Do hide progress bar
    self.hidden = YES;
    
    if (_animationTimer != nil) {
        [_animationTimer invalidate];
        _animationTimer = nil;    
    }
     */
}

- (void) setProgress:(CGFloat)value animated:(BOOL)animated {
    if ((!animated && value > self.progress) || animated) {
        if(loadTimer !=nil){
            self.progress = value;
        }
        
    }
    if(self.progress == 1){
        if(loadTimer != nil){
            [loadTimer invalidate];
            loadTimer = nil;
        }
        
    }
}

- (ChromeProgressBar *)initWithFrame:(CGRect)frame {
	self = [super initWithFrame:frame];
	if(self) {
        //set bar color
        _tintColor = [UIColor redColor];//[[UIColor colorWithRed:51.0f/255.0f green:153.0f/255.0f blue:255.0f/255.0f alpha:1] retain];
		self.progress = 0;
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
	}
    
	return self;
}

- (void)dealloc {

}

-(void)show{
    self.alpha=1;
}
-(void)hide{
    self.alpha=0;
}


@end
